import React,{useState} from 'react'
import JoinRoomInputs from './JoinRoomInputs';
import {connect} from 'react-redux'
import OnlyWithAudoCheckbox from './OnlyWithAudoCheckbox';
import { setConnectOnlyWithAudio,setRoomId,setIdentity } from '../../store/action';
import ErrorMessage from './ErrorMessage';
import JoinRoomButtons from './JoinRoomButtons';
import { getRoomExists } from '../../utils/api';
import { useNavigate } from 'react-router-dom';
const JoinRoomContent = (props) => {
  const {
    isRoomHost,
    setConnectOnlyWithAudio,
    connectOnlyWithAudio,
    setRoomIdAction,
    setIdentityAction,
  } = props;
  const [roomIdValue,setRoomIdValue] = useState('');
  const [nameValue,setNameValue] = useState('');
  const [errorMessage,setErrorMessage] = useState(null);
  let navigate =  useNavigate();
  const hanleJoinRoom = async () =>{
    setIdentityAction(nameValue);
    if (isRoomHost){
      createRoom();
    }else{
      joinRoom();
    }
  }
  const joinRoom = async () =>{
    const responseMessage = await getRoomExists(roomIdValue);
    const {roomExists,full} = responseMessage;
    if (roomExists){
      if (full){
        setErrorMessage('会议房间已满请稍后再试')
      }else{
        setRoomIdAction(roomIdValue)
        navigate('/room');
      }
    }else{
      setErrorMessage('会议房间不存在，请验证ID是否正确')
    }
  }
  const createRoom = ()=>{
    navigate('/room');
  }
  return (
    <>
    <JoinRoomInputs
    roomIdValue={roomIdValue}
    setRoomIdValue = {setRoomIdValue}
    nameValue={nameValue}
    setNameValue={setNameValue}
    isRoomHost={isRoomHost}
    />
    <OnlyWithAudoCheckbox connectOnlyWithAudio={connectOnlyWithAudio} 
    setConnectOnlyWithAudio={setConnectOnlyWithAudio}
    />
    <ErrorMessage errorMessage={errorMessage}/>
    <JoinRoomButtons isRoomHost={isRoomHost} hanleJoinRoom={hanleJoinRoom}/>
    </>
  )
}
const mapStateToProps = (state) => {
  return {
      ...state,
  };
}
const mapActionsToProps = (dispatch) => {
  return {
    setConnectOnlyWithAudio:(onlyWithAudio) => dispatch(setConnectOnlyWithAudio(onlyWithAudio)),
    setRoomIdAction:(roomId)=>dispatch(setRoomId(roomId)),
    setIdentityAction:(identity)=>dispatch(setIdentity(identity)),
  };
};
export default connect(mapStateToProps,mapActionsToProps) (JoinRoomContent)